package com.woniu.zsd.order.service.impl;

import com.woniu.waste.client.WasteClient;
import com.woniu.zsd.commons.core.model.Result;
import com.woniu.zsd.order.dto.StatisticsDto;
import com.woniu.zsd.order.entity.Statistics;
import com.woniu.zsd.order.mapper.StatisticsMapper;
import com.woniu.zsd.order.service.IStatisticsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.zsd.waste.entity.WasteType;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StatisticsServiceImpl extends ServiceImpl<StatisticsMapper, Statistics> implements IStatisticsService {

    @Autowired
    private WasteClient wasteClient;


    @Override
    public List<StatisticsDto> statistics(@Param("startDate")String startDate, @Param("endDate")String endDate) {
        List<Statistics> statisticsList = baseMapper.selectByDateRange(startDate, endDate);
        // 使用 Map 来按 wasteTypeId 分组，并计算每个分组的 price 总和
        Map<Integer, StatisticsDto> wasteTypeMap = new HashMap<>();
        //遍历数组，从中取出wasteTypeId相同的类，并进行数据统计
        for (Statistics statistics : statisticsList) {
            int wasteTypeId = statistics.getWasteTypeId();
            StatisticsDto dto = wasteTypeMap.get(wasteTypeId);
            if (dto == null) {
                dto = new StatisticsDto();
                Result<WasteType> result = wasteClient.getWasteTypeById(wasteTypeId);
                System.out.println(result.toString());
                if (result.getData()!= null) {
                    dto.setWasteTypeName(result.getData().getWasteTypeName());
                    System.out.println(result.getData());
                }
                dto.setQuantity(statistics.getQuantity());
                dto.setPrice(statistics.getPrice());
                dto.setQuantityUnit(statistics.getQuantityUnit());
                wasteTypeMap.put(wasteTypeId, dto);
            } else {
                // 累加 price
                dto.setPrice(dto.getPrice().add(statistics.getPrice()));
                // 累加 quantity
                dto.setQuantity(dto.getQuantity() + statistics.getQuantity());
            }
        }

        // 将 Map 中的值转换为 List 返回
        return new ArrayList<>(wasteTypeMap.values());
    }

}